package com.vpen.account.demo.core;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.vpen.clib.constant.CConstant;
import com.vpen.clib.result.CODE_MSG;
import com.vpen.clib.result.CResult;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author 韦鹏
 * @desc 登录失败处理器
 * @date 2022/7/15 12:04
 **/
@Slf4j
@Component
@AllArgsConstructor(onConstructor_ = @Autowired)
public class LoginFailureHandler extends SimpleUrlAuthenticationFailureHandler {
    private final ObjectMapper objectMapper;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException {
        

        //设置返回请求头
        response.setContentType(CConstant.CONTENT_TYPE);
        //写出流
        PrintWriter out = response.getWriter();
        CResult<String> result;
        if (exception instanceof UsernameNotFoundException || exception instanceof BadCredentialsException || exception instanceof DisabledException) {
            result = CResult.error(CODE_MSG.INVALID);
            String message = exception.getMessage();
            if (StringUtils.isNotBlank(message)) {
                result.setMsg(message);
            }
        } else {
            result = CResult.error(CODE_MSG.UNAUTHORIZED);
        }
        out.write(objectMapper.writeValueAsString(result));
        out.flush();
        out.close();
    }
}
